/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package exterminator.game;

import com.jme3.app.state.AbstractAppState;
import exterminator.Main;
import exterminator.states.HUD;
import exterminator.utils.AudioManager;
import tonegod.gui.core.Screen;
import tonegod.gui.framework.core.util.GameTimer;

/**
 *
 * @author t0neg0d
 */
public class Game extends AbstractAppState {
	public static enum Lost {
		TimesUp,
		Overrun,
		MuckedUp
	}
	
	Main main;
	Screen screen;
	HUD hud;
	GameTimer mainTimer;
	boolean active = true;
	int maxGameTime = 300;
	boolean flagForTimeOut = false;
	
	public Game(Main main, float time) {
		this.main = main;
		this.screen = main.getScreen();
		this.hud = main.getHUD();
		this.maxGameTime = (int)time;
		
		mainTimer = new GameTimer(maxGameTime) {
			@Override
			public void onComplete(float time) {
				hud.updateTimerDisplay(0);
				flagForTimeOut = true;
			}
		};
	}
	
	public int getMaxGameTime() { return this.maxGameTime; }
	
	public void startGame() {
		mainTimer.reset(false);
		screen.getAnimManager().addGameTimer(mainTimer);
		active = true;
		hud.runStartGame();
	}
	
	public void endGame(Lost lost) {
		active = false;
		try {
			screen.getAnimManager().removeGameTimer(mainTimer);
			mainTimer.reset(false);
		} catch (Exception ex) {  }
		hud.runEndGame(lost);
		main.getAudioManager().playAudio(AudioManager.FXKey.LOSE, 1);
	}
	
	public void winGame() {
		active = false;
		hud.runWinGame();
		main.getAudioManager().playAudio(AudioManager.FXKey.WIN, 1);
	}
	
	public boolean getIsGameActive() { return active; }
	
	public void reset() {
		try {
			screen.getAnimManager().removeGameTimer(mainTimer);
		} catch (Exception ex) {  }
		active = false;
		flagForTimeOut = false;
	}
	
	@Override
	public void update(float tpf) {
		if (active) {
			int time = (int)(mainTimer.getDuration()*mainTimer.getPercentComplete());
			time = maxGameTime-time;
			hud.updateTimerDisplay(time);
			if (time == 60)
				main.getAudioManager().updateMusicSpeed(1.15f);
			else if (time == maxGameTime)
				main.getAudioManager().updateMusicSpeed(1f);
			if (flagForTimeOut) {
				endGame(Lost.TimesUp);
				flagForTimeOut = false;
			}
		}
	}
}
